<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="!getBusinessId" :span="12">
          <el-form-item :label="$t('业务类型')" prop="businessType">
            <dictSelect
              v-model="form.businessType"
              :disabled="form.id"
              :clearable="true"
              dictionary="main_body_type_all_crm"
              @input="emptyBusinessId(emptyBusId)"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="!getBusinessId" :span="12">
          <el-form-item :label="$t('主体名称')" prop="businessId">
            <MainBodySelect
              id="businessId"
              v-model="form.businessId"
              :disabled="form.id"
              :parameters="form.businessType"
              :placeholder="$t('请先选择业务类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('姓名')" prop="contactsName">
            <el-input v-model="form.contactsName" maxlength="200" show-word-limit :placeholder="$t('姓名')" @change="isRulesName(form.contactsName)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人类型')" prop="personType">
            <dict-select v-model="form.personType" dictionary="contact_type" :placeholder="$t('联系人类型')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系电话')" prop="phone">
            <el-input v-model="form.phone" maxlength="25" show-word-limit :placeholder="$t('联系电话')" @blur="checkPhone(form.phone)" />
            <div v-if="isPhoneMessage" class="el-form-item__error">{{ '联系电话格式有误' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('性别')" prop="sex">
            <dict-select
              v-model="form.sex"
              dictionary="sys_user_sex"
              :placeholder="$t('性别')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属公司')" prop="company">
            <el-input v-model="form.company" maxlength="100" show-word-limit :placeholder="$t('所属公司')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('职位/角色')" prop="position">
            <el-input v-model="form.position" maxlength="15" show-word-limit :placeholder="$t('职位/角色')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('微信账户')" prop="weChat">
            <el-input v-model="form.weChat" maxlength="30" show-word-limit :placeholder="$t('微信账户')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('电子邮箱')" prop="email">
            <el-input v-model="form.email" maxlength="100" show-word-limit :placeholder="$t('电子邮箱')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('邮箱发送类型')" prop="emailSendingType">
            <dict-select
              v-model="form.emailSendingType"
              dictionary="email_sending_type"
              :clearable="false"
              :placeholder="$t('邮箱发送类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出生年月')" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              clearable
              style="width: 200px"
              type="month"
              value-format="yyyy-MM-dd"
              :placeholder="$t('出生年月')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('城市')" prop="city">
            <el-input v-model="form.city" maxlength="30" show-word-limit :placeholder="$t('城市')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('详细地址')" prop="detailedAddress">
            <el-input v-model="form.detailedAddress" maxlength="200" show-word-limit :placeholder="$t('详细地址')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--过往经历列表-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('过往经历列表') }}</span>
        </div>
        <el-table
          :data="form.contactPastExperienceList"
          border
          class="nowrapTable formTable tree_el_Table"
        >
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('任职公司')" align="center" prop="workCompany">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('任职公司') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'contactPastExperienceList.' + scope.$index + '.workCompany'" :rules="contactPastExperienceListRules.workCompany">
                <el-input v-model="scope.row.workCompany" :placeholder="$t('任职公司')" show-word-limit maxlength="100" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('职位/角色')" align="center" prop="position">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('职位/角色') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'contactPastExperienceList.' + scope.$index + '.position'" :rules="contactPastExperienceListRules.position">
                <el-input v-model="scope.row.position" :placeholder="$t('职位/角色')" show-word-limit maxlength="50" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit maxlength="200" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['contact:person:remove']" type="text" icon="el-icon-delete" @click="delHandleTerms(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addcontactPastExperience">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <FileTable :list.sync="form.fileList" data-type="deal_contacts" :business-id="getBusinessId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
      <el-button v-hasPermi="['contact:person:edit']" type="primary" @mousedown.native="submitForm">{{ $t('保存') }}</el-button>
      <!--      <SaveBtn has-permi="contact:person" />-->
    </div>
  </div>
</template>

<script>
    import { saveDealContacts, getDealContacts, delContactExperience, verifyByContactsName } from '@/api/deal/contact/contactsPerson'
    import MainBodySelect from '@/components/MainBodySelect/index'
    import { getExpertsBase } from '@/api/deal/experts/expertsBase'
    export default {
      components: {
        MainBodySelect
      },
      props: {
        busType: {
          type: String,
          default: undefined
        }
      },
        data() {
            // const checkPhoneAndEmail = (rule, value, callback) => {
            //   if (value !== undefined && value !== '' && value !== null) {
            //     // 校验邮箱
            //     if (rule.field === 'email') {
            //       var regEmail = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
            //       if (!regEmail.test(value)) {
            //         callback(new Error(this.$t('无效邮箱')))
            //       }
            //     }
            //     callback()
            //   } else {
            //     callback()
            //   }
            // }
            return {
                otherBtnHide: false,
                // 表单参数
                form: {
                  fileList: [],
                  contactPastExperienceList: []
                },
                // 业务Id
                getBusinessId: this.$route.query.id,
                // 遮罩层
                loading: false,
              // 记录上一次取消唯一验证时录入的姓名
              lastContactsName: undefined,
              // 记录编辑进入时的姓名
              updateContactsName: undefined,
              // 是否展示手机格式校验
              isPhoneMessage: false,
              // 处理失焦时保存验证两次
              validating: false,
              // 是否清空主体选项
              emptyBusId: false,
                // 表单校验
              rules: {
                contactsName: [{ required: true, validator: this.checkName, trigger: 'blur' }],
                email: [{ required: false, type: 'email', message: this.$t('邮箱格式不正确') }],
                // phone: [{
                //   pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                //   message: this.$t('请输入正确的手机号码'),
                //   trigger: 'blur'
                // }],
                personType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                businessType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                businessId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
              },
              contactPastExperienceListRules: {
                workCompany: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                position: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
              }
            }
        },
        mounted() {
          if (this.getBusinessId === undefined || this.getBusinessId === '' || this.getBusinessId === null) {
            this.getBusinessId = this.$route.query.lpId
          }
          this.emptyBusId = false
        },
        created() {
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealContacts(data.id).then(response => {
                        this.form = response.data
                        this.updateContactsName = this.form.contactsName
                        this.isPhoneMessage = false
                        this.loading = false
                    })
                } else {
                    this.reset()
                    if (this.form.businessId === null || this.form.businessId === undefined || this.form.businessId === '') {
                      this.$nextTick(() => {
                        if (data != null) {
                          this.form.businessId = data.lpId
                        }
                      })
                    }
                    this.isPhoneMessage = false
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                businessId: this.getBusinessId ? this.getBusinessId : undefined,
                businessType: this.busType,
                contactsName: undefined,
                phone: undefined,
                company: undefined,
                position: undefined,
                email: undefined,
                emailSendingType: 'no',
                weChat: undefined,
                fileList: [],
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                contactPastExperienceList: undefined,
                delFlag: undefined,
                  personType: undefined,
                  birthDate: undefined,
                  sex: undefined,
                  city: undefined,
                  detailedAddress: undefined
                }
                this.resetForm('form')
            },

          // 添加过往经历信息
          addcontactPastExperience() {
            const row = {
              id: undefined,
              personId: undefined,
              workCompany: '',
              position: '',
              remark: ''
            }
            if (!(this.form.contactPastExperienceList instanceof Array)) {
              this.$set(this.form, 'contactPastExperienceList', [])
            }
            this.$nextTick(() => {
              this.form.contactPastExperienceList.push(row)
            })
          },
          // 删除过往经历中选中的数据
          delHandleTerms(index, row) {
            // eslint-disable-next-line no-undef
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delContactExperience(id)
                }).then(() => {
                this.form.contactPastExperienceList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.contactPastExperienceList.splice(index, 1)
            }
          },
            // 取消按钮
            cancel() {
                if (this.$parent.$parent.contactOpen !== undefined) {
                  this.$parent.$parent.contactOpen = false
                }
                this.$parent.$parent.formOpen = false
                this.rulesContactsName()
                // this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                if (this.$parent.$parent.contactOpen !== undefined) {
                  this.$parent.$parent.contactOpen = false
                }
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveDealContacts(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.$emit('sendContactPersonData', response.data)
                                this.closeForm()
                                this.rulesContactsName()
                            } else {
                                this.msgError(response.msg)
                                this.loading = false
                            }
                        }).catch(() => {
                          this.rulesContactsName()
                          this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 恢复姓名唯一校验和手机号校验
          rulesContactsName() {
            this.rules.contactsName = [{ required: true, validator: this.checkName, trigger: ['blur'] }]
            this.isPhoneMessage = false
          },
          // 唯一校验确认关闭后若修改姓名则重新校验唯一
          isRulesName(value) {
            if (this.lastContactsName && value !== this.lastContactsName) {
              this.rules.contactsName = [{ required: true, validator: this.checkName, trigger: 'blur' }]
            }
          },
          // 姓名唯一校验
          checkName(rule, value, callback) {
            if (!value) {
              return callback(new Error('必填信息'))
            } else {
              if ((this.form.businessId || this.getBusinessId) && this.form.businessType) {
                if (this.form.businessType === 'experts') {
                  // 业务类型为外部专家时，同一个专家仅能录入一条数据，同时校验姓名与主体名称是否一致；
                  const row = {
                    id: this.form.id ? this.form.id : null,
                    businessId: this.form.businessId
                  }
                  verifyByContactsName(row).then(res => {
                    if (res.msg) {
                      callback(new Error(this.$t('该专家联系人已录入')))
                    } else {
                      getExpertsBase(this.form.businessId).then(res => {
                        console.log(res.data.name, 'res.data.name')
                        if (value !== res.data.name) {
                          callback(new Error(this.$t('该专家姓名与主体名称不一致')))
                        } else {
                          callback()
                        }
                      })
                    }
                  })
                } else {
                  const row = {
                    id: this.form.id ? this.form.id : null,
                    businessId: this.form.businessId,
                    contactsName: value
                  }
                  if (this.form.id) {
                    // 修改时只有修改姓名后才会进行校验
                    if (this.form.contactsName !== this.updateContactsName) {
                      this.verifyByContactsName(row, value, callback)
                    } else {
                      callback()
                    }
                  } else {
                    this.verifyByContactsName(row, value, callback)
                  }
                }
              }
            }
          },
          verifyByContactsName(row, value, callback) {
            if (this.validating) {
              callback()
              return
            }
            this.validating = true
            setTimeout(() => {
              verifyByContactsName(row).then(res => {
                if (res.msg && this.$parent.$parent.formOpen) {
                  this.$confirm(this.$t('该姓名已存在是否要继续录入?'), this.$t('警告'), {
                    confirmButtonText: this.$t('确定'),
                    cancelButtonText: this.$t('取消'),
                    type: 'warning'
                  }).then(() => {
                    this.rules.contactsName = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                    this.lastContactsName = value
                  }).catch(function() {
                  })
                } else {
                  callback()
                }
              })
              this.validating = false
            }, 0)
          },
          // 验证手机号格式
          checkPhone(value) {
            if (value) {
              var reg = /^1[3456789]\d{9}$/
              if (!reg.test(value)) {
                this.isPhoneMessage = true
              } else {
                this.isPhoneMessage = false
              }
            } else {
              this.isPhoneMessage = false
            }
          },
          // 清空二级选项
          emptyBusinessId(empty) {
              if (!this.getBusinessId) {
                if (empty) {
                  this.form.businessId = null
                } else {
                  this.emptyBusId = true
                }
              }
          }
        }

    }
</script>
